<template>
	<div class="match-question-h5-container">
		<!-- 头部：比赛名、剩余时间 -->
		<div class="match-question-h5-header">
			<template v-if="isnot?.isSubmit">
				<div class="match-question-h5-title" style="display: flex; align-items: center; position: relative;">
					<div class="match-question-h5-title-name">
						<div class="match-title-flex">
							<span class="match-name" :title="match?.name || '比赛'">{{ match?.name || '比赛' }}</span>
							<span class="answered-tip">已答题</span>
						</div>
						<!-- 优化后的home图标按钮，右上角浮动 -->
						<div class="home-float-btn" @click="goHome" title="首页">
							<el-icon class="home-float-icon">
								<HomeFilled />
							</el-icon>
						</div>
					</div>
				</div>
			</template>
			<template v-else>
				<!-- 未答题：比赛名和剩余时间分两行 -->
				<div class="match-question-h5-title match-title-block">
					<div class="match-question-h5-title-name">
						<span class="match-name" :title="match?.name || '比赛'">{{ match?.name || '比赛' }}</span>
					</div>
					<div class="match-question-h5-timer timer-block">
						<template v-if="time?.isok">
							答题剩余时间:
							<span class="timer-num">{{ time.d }}</span>天
							<span class="timer-num">{{ time.h }}</span>时
							<span class="timer-num">{{ time.m }}</span>分
							<span class="timer-num">{{ time.s }}</span>秒
						</template>
						<template v-else>
							已结束
						</template>
					</div>
				</div>
			</template>
		</div>
		<!-- 题目内容和答案区域合并卡片，支持独立滚动 -->
		<div class="match-question-h5-main-card scrollable-card" ref="mainCardRef">
			<!-- 代码题 -->
			<Question ref="ques" v-if="question && question.type === '代码'" v-bind="{
				question,
				questionlist: list,
				index: Number(index),
				setuserdata,
				userdata,
				match, isMatch,
				submit,
				readonly: isnot?.isSubmit
			}" />
			<!-- 选择/填空/拍照等题型 -->
			<questionselect ref="select" v-else-if="question && question.type !== '代码'" v-bind="{
				question,
				questionlist: list,
				index: Number(index),
				setuserdata,
				userdata,
				match, isMatch, submit,
				h5: true,
				total: list.length,
				remainStr: time?.isok ? `${time.d}天${time.h}时${time.m}分${time.s}秒` : '',
				readonly: isnot?.isSubmit
			}" />
		</div>
		<!-- 底部按钮区：上一题/下一题/提交 -->
		<div class="match-question-h5-footer">
			<el-button class="match-question-h5-btn" :disabled="Number(index) === 0" @click="toPrev">上一题</el-button>
			<el-button class="match-question-h5-btn" type="primary" v-if="Number(index) < list.length - 1"
				@click="toNext">下一题</el-button>
			<el-button class="match-question-h5-btn" type="primary" v-else :disabled="isnot?.isSubmit"
				@click="submit(true)">提交试卷</el-button>
		</div>
		<!-- 当前题号进度 -->
		<div class="questionselect-h5-progress">
			当前第 {{ Number(index) + 1 }} / {{ list.length }} 题
		</div>
		<!-- 试卷提交内容确认弹窗（H5不再显示，已移除） -->
	</div>
</template>

<script setup lang="ts">

import { useLocalStorage } from "@vueuse/core";
import { ElMessage, ElMessageBox } from "element-plus";
import moment from "moment";
import { Socket } from "socket.io-client";
import { assign } from "underscore";
import {
	computed,
	onMounted,
	ref,
	toRefs,
	watch
} from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import {
	Apimatchuserquestion,
	asyncgettmpmatchuserdata,
	asyncSaveMatch,
	asyncsavetmpmatchuserdata,
	asyncselectmatchquestion,
	jilurizhi,
} from "../../../api";
import { Storekey } from "../../../interface";
import { IWsEmitatactivity } from "../../../mysql_interface";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import { markdownhtml } from "../../../util/htmlstring";
import { SMP } from "./interface";
import Question from "./question.vue";
import questionselect from "./questionselect.vue";
const p = defineProps<{
	index: string
	match: SMP["match"],
	time: SMP["time"],
	matchuser?: Apimatchuserquestion,
	start: Function,
	isnot: { err: number; msg: string, isSubmit?: boolean },
	setresult: Function,
	sub: Boolean,
}>()
const { index, isnot, matchuser } = toRefs(p);
const isMatch = true

const list = ref<Studycodemodel.Imatchquestion[]>([]);
const store = useStore(Storekey);

const router = useRouter();
const user = computed<Studycodemodel.Iuser>(() => {
	return store.getters.getuser;
});

const ques = ref<typeof Question>();
const select = ref<typeof questionselect>();
// 
const userdata_ = useLocalStorage<Record<string, any>>(`${p.match.ID}-${user.value.ID}`, {}) // reactive<Record<string, any>>({});
const userdata = userdata_.value

const question = computed(() => {
	const n = list.value[Number(index.value)]
	if (n) {
		return markdownhtml(n) as Studycodemodel.Imatchquestion
	}
	return null
});
function setuserdata(key: string, context: any) {
	userdata[key] = context;
}

const savetime = ref()
const saveloading = ref(false)

watch(userdata, () => {
	if (!p.match.ID) {
		return;
	}
	saveloading.value = true
	asyncsavetmpmatchuserdata({
		activityid: p.match.ID,
		data: userdata,
		seconds: 1000 * 60 * 60 * 24,
	}).then((e) => {
		saveloading.value = false
		savetime.value = moment().format('HH:mm:ss')
		const t: IWsEmitatactivity = "atactivity";
		store.state.socket.emit(t, {
			activityid: p.match.ID,
			userid: store.state.user?.ID,
		});
	});
});

watch(
	() => index.value,
	(e) => {
		if (Number(p.index) > list.value.length) {
			console.log("题目序号超过列表长度！！！")
			router.push({
				name: "比赛答题",
				params: {
					index: 0,
				},
			});
		}
		// 当前在哪儿一题
		currCheckUq.value = userQuestion.value[Number(e)]
	}
);

// 是否自动提交
watch(() => p.sub, () => {
	if (user.value) {
		// submit();
		_submit();
	}
}
);
const hanzi = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '百']

function save() {
	if (!p.match.ID) {
		return;
	}
	if (ques.value?.context) {
		if (ques.value.context && question.value?.ID) {
			userdata[question.value.ID] = assign({}, userdata[question.value.ID], {
				context: ques.value.context,
				language: ques.value.language || "CPP",
				gccoptimize: ques.value.gccoptimize
			})
		}
	}
}

// 提交试题、试卷 false为提交题目
const isSubmitPaper = ref()
async function submit(b = true) {
	isSubmitPaper.value = b;
	// H5直接提交，不弹窗确认
	_submit(b);
}

async function _submit(b = true) {
	if (!p.match.ID) {
		return;
	}
	if (ques.value) {
		if (ques.value.context && question.value?.ID) {
			userdata[question.value.ID] = {
				context: ques.value.context,
				language: ques.value.language || "CPP",
				gccoptimize: ques.value.gccoptimize
			};
		}
	}
	const socket: Socket = store.state.socket;
	const t = list.value.map((v) => {
		const obj: Studycodemodel.Imatchuserquestion = {};
		if (v.ID) {
			const context = userdata[v.ID];
			obj.type = v.type;
			obj.questionid = v.ID;
			obj.info = {};
			if (v.type !== "代码") {
				obj.questionid;
				obj.info.answer = context;
			} else {
				obj.language = context?.language;
				obj.context = context?.context;
				obj.gccoptimize = context?.gccoptimize ? '-O2' : undefined;
				// 比赛的运行测试和提交代码 需要加上是否文件读写
				obj.isfile = p.match.isfile || false;
			}
			return obj;
		}
		return {};
	});
	if (!b) {
		// socket.emit("match", {
		//   activityid: p.match.ID,
		//   data: [t[Number(index.value)]],
		//   userid: user.value.ID,
		// });
		try {
			await asyncSaveMatch({
				activityid: p.match.ID,
				data: [t[Number(index.value)]],
				userid: user.value.ID,
			})
			ElMessage.success("提交成功");
		} catch (error) {
			ElMessage.error("提交失败");
		}
		return '只提交当前题目'
	}

	// 如果强制提交
	// if (p.sub && socket) {
	//   socket.emit("match", {
	//     activityid: p.match.ID,
	//     data: t,
	//     userid: user.value.ID,
	//   });
	//   router.push({ name: "比赛结束" });
	//   return;
	// }
	if (p.sub) {
		try {
			await asyncSaveMatch({
				activityid: p.match.ID,
				data: t,
				userid: user.value.ID,
			})
			ElMessage.success("提交成功");
			router.push({ name: "比赛结束" });
		} catch (error) {
			ElMessage.error("提交失败");
		}
		return;
	}
	ElMessageBox.confirm(`  <div class="custom-title">是否要提交试卷？</div>`, '提交试卷',
		{
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			dangerouslyUseHTMLString: true,
			customClass: 'custom-message-box',
			// 可选的回调函数，可以根据需求来添加
			// callback: (action) => {
			//   console.log(action)
			// }
		})
		.then(async () => {
			if (!p.match.ID) {
				return;
			}
			console.log(t)
			// socket.emit("match", {
			//   activityid: p.match.ID,
			//   data: t,
			//   userid: user.value.ID,
			// });
			try {
				await asyncSaveMatch({
					activityid: p.match.ID,
					data: t,
					userid: user.value.ID,
				})
				ElMessage.success("提交成功");
			} catch (error) {
				ElMessage.error("提交失败");
				return;
			}
			const arr: [string, any][] = [];

			arr[0] = ["_method_", "match"];
			arr[1] = ["type", "scoket"];
			arr[2] = ["ismatch", true];
			arr[3] = ["matchid", p.match.ID];
			arr[4] = ["matchname", p.match.name];
			jilurizhi(arr);
			router.push({ name: "比赛结束" });
		})
		.catch((e: any) => {
			// ElMessage({ type: 'info', message: '取消提交', })
		});
}

async function Mounted() {
	await p.start();
	if (!user.value) {
		ElMessage.error("请登录");
		router.push({ name: "首页", query: { activityId: p.match.ID } });
	}
	if (!p.match?.ID) {
		router.push({ name: "首页", query: { activityId: p.match.ID } });
		return;
	}
	if (p.match) {
		// TODO 数学比赛 暂时不需要报名
		// const d = p.match.activityuser?.find((v) => v.ID == user.value.ID);
		// if (d) {
		// 	ElMessage.error("没有报名");
		// 	router.push({ name: "首页", query: { activityId: p.match.ID } });
		// }
	}
	if (isnot.value.err) {
		// 判断 isSumbit 是否为true
		console.log("Mounted=>", isnot.value)
		if (isnot.value.isSubmit) {

		} else {
			ElMessage.error(isnot.value.msg);
			router.push({ name: "首页", query: { activityId: p.match.ID } });
		}
	}
	const [data] = await asyncselectmatchquestion({ activityid: p.match.ID, });
	if (data) {
		list.value =
			data.matchquestion?.sort(
				(a, b) => Number(a.paixu) - Number(b.paixu)
			).map((f, k) => {
				if (!p.match.isshowquestionname) {
					return {
						...f,
						name: `第${k + 1}题`
					}
				}
				return f
			}) || [];
	}
	if (list.value.length === 0) {
		ElMessage.error("此次比赛已结束");
		router.push({ name: "首页", query: { activityId: p.match.ID } });
	}
	asyncgettmpmatchuserdata({
		activityid: p.match.ID,
	})
		.then((olddata = {}) => {
			Object.assign(userdata, olddata);
			// 缓存数据获取
			let id;
			if (question.value?.ID) {
				const data = (olddata as any)[question.value.ID];
				if (data) {
					id = data;
				}
			}
			if (ques.value) {
				if (!ques.value.context) {
					ques.value.context = id?.context;
					ques.value.language = id?.language || "CPP";
					// console.log("同步缓存", id, id?.gccoptimize)
					// 为什么gccoptimize是  缓存没有才勾上 有就不勾选
					// ques.value.gccoptimize = id?.gccoptimize === undefined ? true : false
					ques.value.gccoptimize = id?.gccoptimize ? true : false
				}
			}
			if (select.value) {
				if (!select.value.data) {
					select.value.data = id;
				}
			}
		})
		.catch((e) => {
			console.error(e);
		});
}

onMounted(() => {
	Mounted();
});

// 试卷提交内容确认
const dialogVisible = ref(false);
const userQuestionChecked = ref(false);
function toSubmit() {
	userQuestionChecked.value = true;
	_submit(isSubmitPaper.value);
}

const userQuestion = computed(() => {
	return list.value.map((e, i) => {
		if (e.ID) {
			const mySubmit = userdata[e.ID]?.context || "";
			const ret = {
				index: i, ID: e.ID, context: e.context, mySubmit,
				type: e.type, bytes: `${new Blob([mySubmit]).size} 字节`,
				language: userdata[e.ID]?.language
			};
			// 不能直接对外部变量（如 rowData.value）进行赋值，因为计算属性是基于依赖的 缓存 机制的。它只会在其依赖的响应式数据发生变化时 重新计算，并且计算过程中不能进行副作用操作（比如修改其他的响应式变量）。
			// if (!i && !rowData.value) {
			// 	rowData.value = ret
			// }
			return ret
		}
	});
});

const currCheckUq = ref()
function clickRow(row: any, column: any, event: Event): void {
	if (currCheckUq.value?.ID !== row.ID) {
		currCheckUq.value = row
		return
	}
	currCheckUq.value = {}
}
function toQuestion() {
	router.push({ name: '比赛答题', params: { index: currCheckUq.value.index, }, });
	dialogVisible.value = false
}

function rowClassName({ row, rowIndex }: { row: any, rowIndex: number }): string {
	let className = 'cursor-pointer'
	if (currCheckUq.value?.ID === row.ID) {
		className = 'highlight-row cursor-pointer'; // 
	}
	return className;
};

function toPrev() {
	if (Number(index.value) > 0) {
		router.push({ name: "比赛答题", params: { ID: p.match.ID, index: Number(index.value) - 1 } });
	}
}
function toNext() {
	if (Number(index.value) < list.value.length - 1) {
		router.push({ name: "比赛答题", params: { ID: p.match.ID, index: Number(index.value) + 1 } });
	}
}
function goHome() {
	router.push({ name: "首页", query: { activityId: p.match.ID } });
}
</script>

<style scoped>
.match-question-h5-header {
	background: #fff;
	display: flex;
	align-items: center;
	padding: 12px 16px 12px 16px;
	/* 上下边距调整 */
	border-bottom: 1px solid #f0f0f0;
	position: relative;
}

/* 已答题 header 样式（横向） */
.match-question-h5-title {
	font-size: 20px;
	font-weight: bold;
	color: #222;
	margin-bottom: 4px;
	width: 100%;
	display: flex;
	align-items: center;
	position: relative;
}

/* 未答题 header 样式（纵向） */
.match-title-block {
	flex-direction: column;
	align-items: flex-start;
	gap: 6px;
	padding: 0;
	margin: 0;
}

.match-question-h5-title-name {
	flex: 1;
	display: flex;
	align-items: center;
	min-width: 0;
	position: relative;
}

.match-title-flex {
	display: flex;
	align-items: center;
	width: 100%;
	min-width: 0;
	gap: 8px;
}

.match-name {
	font-size: 18px;
	font-weight: bold;
	color: #222;
	margin-right: 10px;
	vertical-align: middle;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
	display: inline-block;
	max-width: calc(100vw - 160px);
}

.answered-tip {
	display: inline-block;
	font-size: 16px;
	font-weight: bold;
	color: #ccc;
	margin-left: 0;
	vertical-align: middle;
	flex-shrink: 0;
	white-space: nowrap;
}

.home-float-btn {
	position: absolute;
	top: 50%;
	right: 0;
	transform: translateY(-50%);
	width: 38px;
	height: 38px;
	background: #409eff;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	cursor: pointer;
	box-shadow: 0 2px 8px rgba(64, 158, 255, 0.12);
	transition: background 0.2s;
	z-index: 10;
}

.home-float-btn:hover {
	background: #66b1ff;
}

.home-float-icon {
	color: #fff;
	font-size: 22px;
}

.match-question-h5-timer {
	color: #409eff;
	font-size: 15px;
	font-weight: 500;
	display: flex;
	align-items: center;
	gap: 2px;
	margin-bottom: 0;
	margin-top: 0;
	padding: 0;
}

.timer-block {
	margin-top: 2px;
	margin-bottom: 0;
}

.timer-num {
	font-size: 16px;
	font-weight: bold;
	color: #e74c3c;
	margin: 0 2px;
}

.match-question-h5-container {
  display: grid;
  grid-template-rows: auto 1fr auto auto;
  height: 100vh;
  overflow: hidden;
}

.match-question-h5-main-card.scrollable-card {
  overflow-y: auto; /* 中间区域可滚动 */
  background: #fff;
  border-radius: 18px;
  margin: 20px 10px 0 10px;
  padding: 0;
  box-shadow: 0 6px 24px rgba(64,158,255,0.08), 0 1.5px 6px rgba(0,0,0,0.04);
}

.match-question-h5-footer {
	display: flex;
	justify-content: space-between;
	margin: 28px 16px 0 16px;
	gap: 12px;
}

.match-question-h5-btn {
	flex: 1;
	height: 42px;
	font-size: 16px;
	border-radius: 21px;
	background: #409eff;
	color: #fff;
	border: none;
}

.match-question-h5-btn:disabled {
	background: #e0e0e0;
	color: #aaa;
}

.questionselect-h5-progress {
	display: flex;
	justify-content: center;
	margin: 18px 0 20px;
	color: #888;
	font-size: 14px;
}

.danger {
	color: #e74c3c;
}

.dialog-body {
	border: 1px solid #ccc;
	height: 60vh;
}

.dialog-footer {
	display: flex;
	align-items: center;
	justify-content: center;
}
</style>
<style>
.custom-message-box .custom-content-b {
	color: red;
}
</style>